package com.gs.process.admin.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gs.process.admin.context.ProcessContext;
import com.gs.process.admin.service.ApprovalService;
import com.gs.process.admin.service.ProcessNodeService;
import com.gs.process.admin.utils.ProcessUtil;
import com.gs.process.model.Approval;
import com.shallowUniverse.logs.annotation.AutoLog;
import com.shallowUniverse.model.Params;
import com.shallowUniverse.web.BaseController;
import com.shallowUniverse.web.annotation.AutoReturn;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

/**
 * @author: Shuai Guo
 * @description:
 * @date: 2021/9/27
 * @version: 1.0
 */
@Controller
@RequestMapping("/approval")
public class ApprovalController extends BaseController {

    @Resource
    private ApprovalService approvalService;
    @Resource
    private ProcessContext processContext;
    @Resource
    private ProcessNodeService processNodeService;

    @AutoLog
    @AutoReturn
    @PostMapping("/find")
    public void find(@RequestBody Params<Approval> params) {
        IPage<Approval> page = approvalService.find(params);
        this.submit(true, page.getRecords()).setTotal((int) page.getTotal());
    }

    @AutoLog
    @AutoReturn
    @PostMapping("/find/user")
    public void findByUser(@RequestBody Params<Approval> params) {
        IPage<Approval> page = approvalService.findByUser(params);
        this.submit(true, page.getRecords()).setTotal((int) page.getTotal());
    }

    @AutoLog
    @AutoReturn
    @PostMapping("/find/role")
    public void findByRole(@RequestBody Params<Approval> params) {
        IPage<Approval> page = approvalService.findByRole(params);
        this.submit(true, page.getRecords()).setTotal((int) page.getTotal());
    }

    @AutoLog
    @AutoReturn
    @GetMapping("/findById/{sid}")
    public void findById(@PathVariable Long sid) {
        Approval approval = approvalService.getById(sid);
        //设置节点和提交人
        approval.setSubmitPerson(processContext.getUser(approval.getUserId()));
        ProcessUtil.populateProcessNode(Collections.singletonList(approval), processNodeService, approvalService);
        this.submit(true, approval);
    }

    @AutoLog
    @AutoReturn
    @PostMapping("/save")
    public void save(@RequestBody Approval approval) {
        boolean result = approvalService.save(approval);
        this.submit(result, approval.getSid());
    }

    @AutoLog
    @AutoReturn
    @DeleteMapping("/delete")
    public void delete(@RequestBody Params<List<Long>> params) {
        boolean result = approvalService.remove(params.getBody());
        this.submit(result, null);
    }
}
